from django.shortcuts import render
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.filters import OrderingFilter

from goods.models import GoodsCategory, SKU
from goods.serializers import ChannelSerializer, CategorySerializer, SKUSerializer, SKUIndexSerializer


class CategoryView(GenericAPIView):
    """商品分类面包屑
    url:categories/pk/
    返回数据:cat1:{url: '', category:{name:'', id:''}}
            cat2: {name:''}
            cat3: {name:''}
    """
    # 指定查询集
    queryset = GoodsCategory.objects.all()

    def get(self, request, pk):
        ret = {
            'cat1': {},
            'cat2': {},
            'cat3': {}
        }
        # 根据pk值从queryset中查询对应的数据模型对象
        category = self.get_object()
        # 判断当前分类
        if not category.parent:
            # 当前类别为一级分类
            # category.goodschannel_set.all()获取到当前一级分类的频道信息查询集，通过下标[0]获取到对象
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodschannel_set.count() == 0:
            # 当前分类为三级分类
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前分类为二级分类
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(category.parent.goodschannel_set.all()[0]).data
        return Response(ret)


class SKUListView(ListAPIView):
    """SKU列表数据
    获取参数：page,page_size,ordering
    url:/categories/pk/skus/
    返回数据：count,results
    """
    # 指定序列化器
    serializer_class = SKUSerializer
    # 增加排序功能[drf本身提供一个对列表页进行排序的功能]
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    def get_queryset(self):
        """指定查询集"""
        # self.kwargs　指代获取路由中的正则参数的值，drf内部的APIView视图类中声明的
        category_id = self.kwargs['category_id']
        # 查询满足为当前分类且上架状态的商品
        return SKU.objects.filter(category=category_id, is_launched=True)


class SKUSearchViewSet(HaystackViewSet):
    """SKU搜索"""
    index_models = [SKU]
    serializer_class = SKUIndexSerializer
